package br.leiam.eolica.BD;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Random;

import br.leiam.eolica.excecoes.EolicaException;
import br.leiam.eolica.util.Logger;

public class Consulta {

	private final String queryString;
	private ResultSet resultSet;
	private int numeroDeLinhas;
	protected Connection conexao;

	public Consulta(String queryString) throws EolicaException {
		this.queryString = queryString;
		
		executar();
	}

	public synchronized void executar() throws EolicaException {
		conexao = getConexao();
		try {
			Statement stmt = conexao.createStatement(
					ResultSet.TYPE_SCROLL_INSENSITIVE,
					ResultSet.CONCUR_READ_ONLY);

			Logger.getInstance().log("Consulta iniciada: " + queryString);			
			setResultSet(stmt.executeQuery(queryString));
			Logger.getInstance().log("Consulta Finalizada");
			resultSet.last();
			setNumeroDeLinhas(resultSet.getRow());

		} catch (SQLException e) {
			Logger.getInstance().log("Erro na Consulta: "+ e.getStackTrace());
			e.printStackTrace();
			
			throw new EolicaException("Erro na consulta");
		}
	}

	public Object getValorEm(int row, int column) {
		try {
			resultSet.absolute(row + 1);
			return resultSet.getObject(column + 1);
		} catch (SQLException sqlException) {
			sqlException.printStackTrace();
		}
		return "";
	}

	protected synchronized Connection getConexao() throws EolicaException {
		Connection conexao = Conexao.getConexao();
		try {
			if(conexao.isClosed())
				Conexao.conectar();			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return conexao;
	}

	private void setResultSet(ResultSet resultSet) {
		this.resultSet = resultSet;
	}

	public ResultSet getResultSet() {
		return resultSet;
	}

	private void setNumeroDeLinhas(int numeroDeLinhas) {
		this.numeroDeLinhas = numeroDeLinhas;
	}

	public int getNumeroDeLinhas() {
		return numeroDeLinhas;
	}

}
